//
//  WBHomeTableViewController.swift
//  weibo
//
//  Created by yanghong on 15/12/5.
//  Copyright © 2015年 杨鸿. All rights reserved.
//

import UIKit
import SVProgressHUD
// tableViewcell 的重用标示符
let WBHomeTableViewCellId = "HOMECELL"
class WBHomeTableViewController: WBVisitorTableViewController {
    
    var homeListViewModle: WBHomeListViewModel = WBHomeListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isUserLogin {
            
            visitorView?.setVisitorInfo(nil , message: nil)
            return
        }
        setupNav()
        loadData()
    }
    
    private func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch",  target: self, action: "friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop",  target: self, action: "friendsearch")
        
        setupTableView()
        
    }
    //设置tableView
    private func setupTableView() {
        //注册cell
        
        tableView.registerClass(WBStatusesCell.self, forCellReuseIdentifier: WBHomeTableViewCellId)
        
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.estimatedRowHeight = 500
        
        tableView.tableFooterView = pullUpView
        
        tableView.separatorStyle = .None
        
        tableView.addSubview(homeRefreshControl)
        
      homeRefreshControl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)

        
    }
    
   func refreshData(refreshControl: WBRefreshControl){
       
        // 过5秒之后再回调
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
           
            self.loadData()
        })
    }
    
    @objc private func friendsearch() {
        
        navigationController?.pushViewController(WBTempViewController(), animated: true)
        
    }
    
    // MARK -  懒加载控件
    
    private lazy var pullUpView: UIActivityIndicatorView = {
        
        let pullUpView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        pullUpView.color = UIColor.darkGrayColor()
        
        pullUpView.sizeToFit()
        
        // pullUpView.startAnimating()
        
        return pullUpView
        
    }()
    
    //懒加载 下拉刷新
    
    private  var homeRefreshControl: WBRefreshControl = WBRefreshControl()
    
    //下拉刷新的提示控件
    
    private lazy var pullDownTipLabel: UILabel = {
        
        let label = UILabel()
        
        label.backgroundColor = UIColor.orangeColor()
        label.font = UIFont.systemFontOfSize(12)
        label.textAlignment = .Center
        label.textColor = UIColor.whiteColor()
        label.hidden = true
        var frame = label.frame
        frame.size = CGSizeMake(SCREENWIDTH, 35)
        frame.origin.y = 64 - 35
        label.frame = frame
        return label
    }()
}



// MARK -  tableView dataSourceDelegate
extension WBHomeTableViewController {
    // 返回多少行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeListViewModle.homeList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //
        let  cell = tableView.dequeueReusableCellWithIdentifier(WBHomeTableViewCellId, forIndexPath: indexPath) as! WBStatusesCell
        
        cell.statusesViewModel = homeListViewModle.homeList![indexPath.row]
        
        return cell
    }
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if !pullUpView.isAnimating() && indexPath.row == homeListViewModle.homeList!.count - 1 {
            
            pullUpView.startAnimating()
            
            loadData()
            
        }
    }
}

// MARK - 加载微博数据
extension WBHomeTableViewController {
    
   @objc private func loadData() {
        
        homeListViewModle.loadData(pullUpView.isAnimating()) { (isSuccessed, count) -> () in

            if isSuccessed {
                //如果请求回来数据,就刷新数据
                self.tableView.reloadData()
                
                if !self.pullUpView.isAnimating() {
                
                    self.showPullDownTips(count)
                }
                
            }else{
                
                SVProgressHUD.showErrorWithStatus("数据请求失败")
            }
              self.endLoad()
        }
 
    }
    // MARK -  tip
    
    private func showPullDownTips(count: Int) {
        //当控件正在执行动画,直接返回
        if pullDownTipLabel.hidden == false {
            
            return
            
        }
        if self.pullDownTipLabel.superview == nil {
            
            if let navController = self.navigationController {
                
                navController.view.insertSubview(self.pullDownTipLabel, belowSubview: navController.navigationBar)
                
            }
            
        }
        if count == 0 {
            
            self.pullDownTipLabel.text = "没有新的微博"
            
        }else{
            
            self.pullDownTipLabel.text = "有\(count)条新微博"
        }
        pullDownTipLabel.hidden = false
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, self.pullDownTipLabel.frame.size.height)
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    
                    }, completion: { (_) -> Void in
                        
                        self.pullDownTipLabel.hidden = true
                })
                
                
        }
        
        
    }
    
    private func endLoad() {
        
        pullUpView.stopAnimating()
        
        homeRefreshControl.endRefresh()
    }
    
}
